<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Babylon.js WebAR Demo</title>
    <script src="https://cdn.babylonjs.com/babylon.js"></script>
    <!-- 用于 AR 的额外模块 -->
    <script src="https://cdn.babylonjs.com/gui/babylon.gui.js"></script>
    <style>
        html, body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        #renderCanvas {
            width: 100%;
            height: 100%;
            touch-action: none;
        }
    </style>
</head>
<body>
    <canvas id="renderCanvas"></canvas>
    <script>
        const startAR = async () => {
            const canvas = document.getElementById("renderCanvas");
            const engine = new BABYLON.Engine(canvas, true);
            const scene = new BABYLON.Scene(engine);

            // ----------------------------
            // 1. 启用 WebXR AR 功能
            // ----------------------------
            const xr = await scene.createDefaultXRExperienceAsync({
                // 指定 AR 模式
                disableDefaultUI: true,
                floorMeshes: []
            });

            // 检查是否支持 AR
            if (!xr.baseExperience) {
                alert("当前浏览器不支持 WebXR AR！");
                return;
            }

            // ----------------------------
            // 2. 添加 AR 提示界面
            // ----------------------------
            const guiTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
            const textBlock = new BABYLON.GUI.TextBlock();
            textBlock.text = "点击屏幕放置模型";
            textBlock.color = "white";
            textBlock.fontSize = 24;
            guiTexture.addControl(textBlock);

            // ----------------------------
            // 3. 加载 3D 模型（示例使用内置模型）
            // ----------------------------
            let model; // 用于存储要放置的模型

            // 点击屏幕时放置模型
            scene.onPointerDown = async (evt) => {
                if (!model) {
                    // 创建模型（例如一个盒子）
                    model = BABYLON.MeshBuilder.CreateBox("box", { size: 0.1 }, scene);
                    model.material = new BABYLON.StandardMaterial("mat", scene);
                    model.material.diffuseColor = new BABYLON.Color3(1, 0, 0); // 红色

                    // 将模型绑定到 AR 锚点
                    const anchor = new BABYLON.TransformNode("anchor");
                    model.parent = anchor;

                    // 使用 hitTest 将模型放置在现实世界的平面上
                    const hitTestResult = await xr.baseExperience.sessionManager.session.requestHitTest(
                        new XRRay(evt.pointerX, evt.pointerY),
                        xr.baseExperience.sessionManager.referenceSpace
                    );

                    if (hitTestResult && hitTestResult.length > 0) {
                        const pose = hitTestResult[0].getPose(xr.baseExperience.sessionManager.referenceSpace);
                        anchor.position.copyFrom(pose.transform.position);
                        anchor.rotationQuaternion.copyFrom(pose.transform.orientation);
                    }

                    textBlock.text = "模型已放置！";
                }
            };

            // ----------------------------
            // 4. 启动渲染循环
            // ----------------------------
            engine.runRenderLoop(() => scene.render());
            window.addEventListener("resize", () => engine.resize());
        };

        // 启动 AR
        startAR().catch((err) => console.error("AR 初始化失败:", err));
    </script>
</body>
</html>